<?php
	require_once ("../includes/config.php");
	//Check authorization
	if ($_SESSION['r'] > 1)
	{
		$_SESSION['error_message'] = "غير مسموح";
		redirect("index.php");
		die();
	}
	//Making Sure The Image Size Isn't Bigger Than X and Y and resize it if needed
	function image_resize($image, $dwidth = 100, $dheight = 100)
	{
		//get image size
		list($nwidth, $nheight) = list($width, $height) = getimagesize($image);

		//save unnecessary work
		if ($nwidth <= $dwidth && $nheight <= $dheight)
		{
			return true;
		}

		//calculate new width and height if needed
		if ($nwidth > $dwidth)
		{
			$nwidth = $dwidth;
			$nheight = (int)((($nwidth / $width) * $nheight) + 0.5);
		}
		if ($nheight > $dheight)
		{
			$nheight = $dheight;
			$nwidth = (int)((($nheight / $height) * $nwidth) + 0.5);
		}

		//get file extention aka file type and create the related resource
		$type = @strtolower(array_pop(explode(".", $image)));
		$imagex = $image;
		if ($type == "jpg" || $type == "jpeg")
		{
			$image = imagecreatefromjpeg($image);
		}
		elseif ($type == "gif")
		{
			$image = imagecreatefromgif($image);
		}
		elseif ($type == "png")
		{
			$image = imagecreatefrompng($image);
		}

		//create a new resource for the new resized image
		$image_p = imagecreatetruecolor($nwidth, $nheight);
		if (!($image && $image_p))
		{
			return false;
		}
		elseif ($type == "png" || $type == "gif")
		{
			imagealphablending($image_p, false);
			imagesavealpha($image_p, true);
		}

		//Resize the image and output it to a new file
		if (imagecopyresampled($image_p, $image, 0, 0, 0, 0, $nwidth, $nheight, $width, $height))
		{
			if ($type == "jpg" || $type == "jpeg")
			{
				if (!imagejpeg($image_p, $imagex . "_temp", 90))
				{
					return false;
				}

			}
			elseif ($type == "gif")
			{
				if (!imagegif($image_p, $imagex . "_temp"))
				{
					return false;
				}
			}
			elseif ($type == "png")
			{
				if (!imagepng($image_p, $imagex . "_temp", 1))
				{
					return false;
				}
			}
			else
			{
				return false;
			}

		}
		else
		{
			return false;
		}

		//If everything is fine overwrite the old image :)
		if (rename($imagex . "_temp", $imagex))
		{
			return true;
		}
		else
		{
			return false;
		}

	}

	if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['type']) && $_POST['type'] != "")
	{
		if ($_SESSION["r"] == 0)
		{
			$sql = query('SELECT * FROM apartments_owner WHERE user_id=?', $_POST['user_id']);
		}
		elseif ($_SESSION["r"] == 1)
		{
			$sql = query('SELECT * FROM apartments_owner WHERE user_id=? and id=?', $_POST['user_id'], $_SESSION['id']);
		}

		if (!empty($sql))
		{
			$sql = $sql[0];
			if (isset($_POST['oldpass']) && $_POST['oldpass'] == $_POST['password'])
			{
				$pass = $_POST['password'];
			}
			else
			{
				$pass = sha1($_POST['password']);
			}

			$q = "UPDATE apartments_owner SET ";
			if ($_SESSION["r"] == 1 && $_POST["type"] > 1)
			{
				$q .= "first_name= ? ,role= ?,last_name= ? ,username= ? , password= ? ,email= ? ,phone= ? WHERE user_id= ?";
				$a = array(
					$_POST['first_name'],
					$_POST['type'],
					$_POST['last_name'],
					$_POST['username'],
					$pass,
					$_POST['email'],
					$_POST['phone'],
					$_POST['user_id']
				);
			}
			elseif ($_SESSION["r"] == 0 && $_POST["type"] <= 1)
			{
				//Logo Dir
				$lname = "";
				//Check the logo file
				if (isset($_FILES["hlogo"]))
				{
					//check for errors
					if ($_FILES["hlogo"]["error"] > 0)
					{
						//$_SESSION['error_message']="Error: " . $_FILES["hlogo"]["error"];
						//Do Nothing
					}
					else
					{
						//make sure that the file doesn't already exists
						while (file_exists("./images/logos/" . $_FILES["hlogo"]["name"]))
						{
							$_FILES["hlogo"]["name"] = mt_rand(100, 10000) . "_" . $_FILES["hlogo"]["name"];
						}
						//Copy the file to the correct dir and resize it
						if (rename($_FILES["hlogo"]["tmp_name"], "./images/logos/" . $_FILES["hlogo"]["name"]))
						{
							if (!image_resize("./images/logos/" . $_FILES["hlogo"]["name"]))
							{
								unlink("./images/logos/" . $_FILES["hlogo"]["name"]);
							}
							else
							{
								$lname = "./images/logos/" . $_FILES["hlogo"]["name"];
							}
						}
					}
				}

				if ($sql['role'] <= 1)
				{
					if ($lname == "")
					{
						$lname = $sql['logo'];
					}
					else
					{
						unlink($sql['logo']);
					}

					$q .= "first_name= ? ,role= ?,last_name= ? ,username= ? , password= ? ,email= ? ,phone= ?,orgnanization_name=?,ophone=?,ofax=?,oweb=?,logo=? WHERE user_id= ?";
					$a = array(
						$_POST['first_name'],
						$_POST['type'],
						$_POST['last_name'],
						$_POST['username'],
						$pass,
						$_POST['email'],
						$_POST['phone'],
						$_POST["hname"],
						$_POST["htel"],
						$_POST["hfax"],
						$_POST["hweb"],
						$lname,
						$_POST['user_id']
					);
				}
				elseif ($sql['role'] > 1)
				{
					$q .= "id=? ,first_name= ? ,role= ?,last_name= ? ,username= ? , password= ? ,email= ? ,phone= ?,orgnanization_name=?,ophone=?,ofax=?,oweb=?,logo=? WHERE user_id= ?";
					$a = array(
						$sql['user_id'],
						$_POST['first_name'],
						$_POST['type'],
						$_POST['last_name'],
						$_POST['username'],
						$pass,
						$_POST['email'],
						$_POST['phone'],
						$_POST["hname"],
						$_POST["htel"],
						$_POST["hfax"],
						$_POST["hweb"],
						$lname,
						$_POST['user_id']
					);
				}
			}
			elseif ($_SESSION["r"] == 0 && $_POST["type"] > 1 && $sql['role'] > 1)
			{
				$q .= "first_name= ? ,role= ?,last_name= ? ,username= ? , password= ? ,email= ? ,phone= ? WHERE user_id= ?";
				$a = array(
					$_POST['first_name'],
					$_POST['type'],
					$_POST['last_name'],
					$_POST['username'],
					$pass,
					$_POST['email'],
					$_POST['phone'],
					$_POST['user_id']
				);
			}
			else
			{
				$_SESSION['error_message'] = "حدث خطأ";
				redirect("usersManage.php");
			}
			$update = query($q, $a);

			$_SESSION['success_message'] = "تم تعديل المستخدم بنجاح";
			redirect("usersManage.php");
		}
		else
		{
			$_SESSION['error_message'] = "اسم المستخدم موجود مسبقاً";
			redirect("usersManage.php");
		}
	}
	else
	{
		$_SESSION['error_message'] = "حدث خطأ";
		redirect("usersManage.php");
	}
?>